package cn.wolfcode.wolf2w.service.impl;


import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.StrategyCatalogQueryObject;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.vo.CatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
//@Transactional mongodb事务必须复制集方式
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {
    @Autowired
    private StrategyCatalogRepository repository;
    @Autowired
    private MongoTemplate template;
    @Autowired
    private IStrategyService strategyService;

    @Override
    public void save(StrategyCatalog strategyCatalog) {
        strategyCatalog.setId(null);//防止游标
        repository.save(strategyCatalog);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {
        repository.save(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public StrategyCatalog get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyCatalog> list() {
        return repository.findAll();
    }

    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQueryObject qo) {
        //查询的条件对象
        Query query = new Query();
        //拼接条件
        long count = template.count(query, StrategyCatalog.class);//计算一共有多少条数据 query 为无条件 totalCount  集合MOngoDb
        if (count == 0) {
            return Page.empty();//空的页面对象
        }
        //分页加排序---->条件拼接
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        //把条件放入查询对象中
        query.with(pageRequest);
        //查询当前结果集template.find
        List<StrategyCatalog> list = template.find(query, StrategyCatalog.class);
        //PageImpl等价于之前的PageResult
        return new PageImpl<>(list, pageRequest, count);//PageResult原生的  pageRequest当前页  多少条数
        //PageHadler  分页插件的
    }


    public void saveOrUpdate(StrategyCatalog strategyTheme) {
        if (StringUtils.hasLength(strategyTheme.getId())) {
            repository.save(strategyTheme);
        } else {
            strategyTheme.setId(null);
            template.insert(strategyTheme);
        }
    }

    @Override
    public List<CatalogVO> groupList() {
        List<CatalogVO> list = new ArrayList<>();
        TypedAggregation<StrategyCatalog> agg = Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        push("name").as("names").
                        push("id").as("ids")
        );
        AggregationResults<Map> result = template.aggregate(agg, Map.class);
        List<Map> datas = result.getMappedResults();
        for (Map data : datas) {
            CatalogVO vo = new CatalogVO();
            vo.setDestName(data.get("_id").toString());
            List<Map<String, Object>> mm = new ArrayList<>();
            List<Object> names = (List<Object>) data.get("names");
            List<Object> ids = (List<Object>) data.get("ids");
            for (int i = 0; i < names.size(); i++) {
                Map<String, Object> vv = new HashMap<>();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                vv.put("id", id);
                vv.put("name", name);
                mm.add(vv);
            }
            vo.setMapList(mm);
            list.add(vo);
        }
        System.out.println(list);
        return list;
    }

    @Override
    public List<StrategyCatalog> getByDestId(String destId) {
        List<StrategyCatalog> strategyCatalogs = repository.findByDestId(destId);

        for (StrategyCatalog strategyCatalog : strategyCatalogs) {
            strategyCatalog.getDestId();
            List<Strategy> byDestId = strategyService.getByCatalogName(strategyCatalog.getName());
            strategyCatalog.setStrategies(byDestId);
        }
        return strategyCatalogs;
    }
}